package com.email.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.sql.rowset.CachedRowSet;

import com.email.base.DBConnection;
import com.sun.rowset.CachedRowSetImpl;

/**
 * 将数据库中的树信息表与JsonBean关联
 * @author victor
 *
 */
public class JsonDao {
	private static JsonDao instance;

	private JsonDao() {}

	/**
	 * 获取FolderDao类的实例
	 * @return
	 */
	public static JsonDao getInstance() {
		if (instance == null) {
			instance = new JsonDao();
		}
		return instance;
	}
	
	/**
	 * 获取当前用户下指定parent_id树信息，需要注意的是这里使用了递归调用。
	 * @param parent_id
	 * @param username
	 * @return
	 * @throws SQLException 
	 */
	public JsonBean[] getArrays(Integer parent_id, String username) throws SQLException{
		JsonBean[] jsonbean = null;
		ArrayList<JsonBean> jsonList = null;
		String sql = "select * from tree where username= '"+username+"' and parent_id = "+parent_id+" ";
		Connection connect = DBConnection.getConnection();
		Statement stmt = null;
		ResultSet rs = null;
		CachedRowSet cs = null;
		try {
			stmt = connect.createStatement();
			rs = stmt.executeQuery(sql);
		    cs = new CachedRowSetImpl();
		    jsonList = new ArrayList<JsonBean>();
		    cs.populate(rs); 
			while(cs.next()){
				JsonBean jsonBean = new JsonBean();
				jsonBean.setKey(new Integer(cs.getInt("id")).toString());
				jsonBean.setActivate(getBoolean(cs.getInt("activate")));
				jsonBean.setAddClass(cs.getString("addClass"));
				jsonBean.setExpand(getBoolean(cs.getInt("expand")));
				jsonBean.setFocus(getBoolean(cs.getInt("focus")));
				jsonBean.setHideCheckbox(getBoolean(cs.getInt("hideCheckbox")));
				jsonBean.setHref(cs.getString("href"));
				jsonBean.setIcon(cs.getString("icon"));
				jsonBean.setLazy(getBoolean(cs.getInt("isLazy")));
				jsonBean.setNoLink(getBoolean(cs.getInt("noLink")));
				jsonBean.setSelect(getBoolean(cs.getInt("select")));
				jsonBean.setTitle(cs.getString("title"));
				jsonBean.setTooltip(cs.getString("tooltip"));
				jsonBean.setUnselectable(getBoolean(cs.getInt("unselectable")));
				jsonBean.setChildren(getArrays(new Integer(jsonBean.getKey()), username));
				jsonList.add(jsonBean);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		jsonbean = new JsonBean[jsonList.size()];
		jsonbean = jsonList.toArray(jsonbean);
		cs.close();
	    stmt.close();
	    connect.close();
		return jsonbean;
	}
	
	public boolean getBoolean(int i){
		if(i==1){
			return true;
		}else{
			return false;
		}
	}
	
	public static void main(String[] args){
		JsonBean[] jsonArrays = null;
		try {
			jsonArrays = JsonDao.getInstance().getArrays(-1, "test");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println(Object_Json.getInstance().arrays2Json(jsonArrays));
	}	
}
